  require 'digest/sha2'

  # t.string  :username
  # t.string  :email
  # t.string  :hashed_password
  # t.string  :salt
  # t.integer :admin,  :default => 0      
  # t.timestamps  
  
  class User < ActiveRecord::Base
    attr_accessor :new_password, :new_password_confirmation
    # Ensure that all required data was provided
    validates :username, :email, :presence => { :message => 'You must provide this value' }    
    # Ensure that the username is unique
    validates :username, :uniqueness => { :case_sensitive => false, :message => 'Username is in use' }  
    # Ensure that the email is approximately and email address (this is not perfect, but it is close enough)
    validates :email, :format => {:with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => 'Enter valid email address.'}
    
    # If the password is being changed, be sure that the confirm password is correct
    validates :new_password, :confirmation => { :message => 'Passwords must match' }, :if=>:password_changed?
    
    before_save :hash_new_password, :if=>:password_changed?
    
    # See if a new password was provided
    def password_changed?
      !@new_password.blank?
    end
    
    def self.authenticate(username, password)
      if user = find_by_username(username)
        if user.hashed_password == Digest::SHA2.hexdigest(user.salt + password)
          return user
        end
      end 
      return nil
    end    
    
    private
    # Generate a new salt and a new password
    def hash_new_password
      self.salt = ActiveSupport::SecureRandom.base64(8)
      self.hashed_password = Digest::SHA2.hexdigest(self.salt + @new_password)
    end
  end
